var addTwoNumbers = function(l1, l2) {
  var leftArr = toArray(l1).reverse();
  var rightArr = toArray(l2).reverse();
  var charArr = addTwoArra(leftArr, rightArr);
  var result = new ListNode();
  var current = result;
  var loop = charArr.length;
  while (loop--) {
    var elem = charArr[loop];
    current.val = elem;
    if (loop != 0) {
      var next = new ListNode();
      current.next = next
      current = next
    }
  }
  return result
};

function toArray(elem) {
  var array = []
  while (elem) {
    array.push(elem.val)
    elem = elem.next
  }
  return array
}

function addTwoArra(leftArr, rightArr) {
  var leftLen = leftArr.length;
  var rightLen = rightArr.length;
  var maxLen = Math.max(leftLen, rightLen);
  var minLen = Math.min(leftLen, rightLen);
  var resultArr = new Array(maxLen);
  if (leftLen > rightLen) {
    resultArr = leftArr.slice();
  } else {
    resultArr = rightArr.slice();
  }
  var step = 1; //步长
  var flag = 0; //10进制进位
  do {
    var leftVal = leftArr[leftLen - step];
    var rightVal = rightArr[rightLen - step];
    var sumVal = leftVal + rightVal + flag;
    flag = 0;
    if (sumVal >= 10) {
      flag = 1; //下次相加加上flag
      resultArr[maxLen - step] = (sumVal % 10)
    } else {
      resultArr[maxLen - step] = sumVal
    }
    step++
  } while (step <= minLen)
  if (flag == 1) { //头位需要进位
    jinwei(resultArr, (maxLen - minLen) - 1);
  }
  return resultArr
  //进位
  function jinwei(arra, len) {
    if (len < 0) {
      arra.unshift(1) //已经超出最大数组范围
      return
    }
    var val = arra[len]++;
    if (val == 10) {
      arra[len] = 0
      jinwei(arra, --len)
    } else {
      arra[len] = val
    }
  }
}